# -*-coding: utf-8 -*-
# by zw on 2017/12/20
import logging
from utils.util import get_valid_yaml, merge_dicts
from sanic import response
from utils.mongo import get_resource_config_collection
from sanic import Blueprint

bp = Blueprint('resource_config', url_prefix='')
_logger = logging.getLogger(__name__)


@bp.get("resource_config")
async def get_get_resource_config_collection(request):
    try:
        type = request.raw_args['type']
        _logger.info("  host %s", request.host)
        res = get_resource_config_collection().find_one({"type": type},
                                                              {"_id": 0})
        return response.json({"code": 0, "message": "", "data": res, })
    except Exception as e:
        _logger.exception("url %s exception %s" % (request.url, e))
        return response.json({"code": 4003, "message": "error message %s" % e, "data": {}})


@bp.post("resource_config")
async def add_get_resource_config_collection(request):
    try:
        _json = request.json
        type = _json["type"]
        yaml_str = _json["yaml_str"]
        _logger.info(" config %s host %s", yaml_str, request.host)
        resource_data = get_valid_yaml(yaml_str)
        if not resource_data:
            return response.json({"code": 4003, "message": "yaml str %s invalid" % yaml_str, "data": {}})
        resource_values = list(resource_data.values())
        if len(resource_values) != len(set(resource_values)):  # 重复的资源值
            return response.json({"code": 4003, "message": "yaml str %s value duplicate" % yaml_str, "data": {}})

        get_resource_config_collection().find_one_and_update({"type": type},
                                                                   {"$set": {"yaml_str": yaml_str}},
                                                                   upsert=True)
    except Exception as e:
        _logger.exception("url %s" % request.url)
        return response.json({"code": 4003, "message": "error message %s" % e, "data": {}})
    else:
        return response.json({"code": 0, "message": "", "data": {}})
